<template>
    <!-- 查询条件表单-新增按钮-启用禁用按钮 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名：">
            <el-input v-model="searchForm.name" placeholder="姓名" clearable />
        </el-form-item>

        <el-form-item label="工资：">
            <el-input v-model="searchForm.salary" placeholder="工资" clearable />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" plain :icon="Search" @click="find">查询</el-button>
            <el-button type="primary" plain :icon="DocumentAdd" @click="dialogAddFormVisible = true">新增</el-button>
            <el-button type="success" plain :icon="CircleCheck" @click="modifyStatus('1')">启用</el-button>
            <el-button type="danger" plain :icon="CircleClose" @click="modifyStatus('0')">禁用</el-button>
        </el-form-item>
    </el-form>


    <!-- 表格 -->
    <el-table :data="pageModel.tableData" stripe style="width: 100%" highlight-current-row @current-change="handlerCurrentRowChange">
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" :formatter="sexFormatter" />
        <el-table-column prop="salary" label="工资" />
        <el-table-column prop="hireDate" label="入职时间" :formatter="dateFormatter"/>
        <el-table-column label="状态">
            <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status == '1' ? '启用':'禁用' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" size="small" :icon="Edit" @click="showModify(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="remove(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div>
        <el-pagination
            v-model:current-page="searchForm.pageNo"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[2, 5, 10]"
            :disabled="disabled"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageModel.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>

    <!-- 新增模态框 -->
    <el-dialog v-model="dialogAddFormVisible" title="员工新增" width="700" @close="clear">
        <el-form :model="empForm" label-width="auto" style="max-width: 600px;">
            <el-form-item label="姓名：">
                <el-input v-model="empForm.name" autocomplete="off" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="工资：">
                <el-input v-model="empForm.salary" autocomplete="off" type="password" show-password placeholder="请输入工资" clearable />
            </el-form-item>
            <el-form-item label="性别：">
                <el-radio-group v-model="empForm.sex">
                    <el-radio value="1">男</el-radio>
                    <el-radio value="0">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="学历：">
                <el-select v-model="empForm.edu" placeholder="请选择学历" clearable>
                    <el-option
                        v-for="option in options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="爱好：">
                <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                >
                    全选&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </el-checkbox>
                <el-checkbox-group
                    v-model="empForm.hobbies"
                    @change="handleCheckedHobbiesChange"
                >
                    <el-checkbox v-for="hobby in hobbies" :key="hobby.value" :label="hobby.label" :value="hobby.value">
                        {{ hobby.label }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="简介：">
                <el-input v-model="empForm.description" type="textarea" autocomplete="off" style="width: 800px;" rows="4" placeholder="请输入简介" />
            </el-form-item>
            <el-form-item label="日期：">
                <el-date-picker
                    v-model="empForm.hireDate"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY年MM月DD日"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogAddFormVisible = false">取消</el-button>
                <el-button type="primary" @click="add">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 修改模态框 -->
     <el-dialog v-model="dialogEditFormVisible" title="员工修改" width="700" @close="clear">
        <el-form :model="empForm" label-width="auto" style="max-width: 600px;">
            <el-form-item label="姓名：">
                <el-input v-model="empForm.name" autocomplete="off" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="工资：">
                <el-input v-model="empForm.salary" autocomplete="off" type="password" show-password placeholder="请输入工资" clearable />
            </el-form-item>
            <el-form-item label="性别：">
                <el-radio-group v-model="empForm.sex">
                    <el-radio value="1">男</el-radio>
                    <el-radio value="0">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="学历：">
                <el-select v-model="empForm.edu" placeholder="请选择学历" clearable>
                    <el-option
                        v-for="option in options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="爱好：">
                <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                >
                    全选&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </el-checkbox>
                <el-checkbox-group
                    v-model="empForm.hobbies"
                    @change="handleCheckedHobbiesChange"
                >
                    <el-checkbox v-for="hobby in hobbies" :key="hobby.value" :label="hobby.label" :value="hobby.value">
                        {{ hobby.label }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="简介：">
                <el-input v-model="empForm.description" type="textarea" autocomplete="off" style="width: 800px;" rows="4" placeholder="请输入简介" />
            </el-form-item>
            <el-form-item label="日期：">
                <el-date-picker
                    v-model="empForm.hireDate"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY年MM月DD日"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogEditFormVisible = false">取消</el-button>
                <el-button type="primary" @click="modify">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>


</template>

<script setup>
import { ref,reactive, onMounted } from 'vue';
import { Search,DocumentAdd,CircleCheck,CircleClose,Edit,Delete } from '@element-plus/icons-vue'
import * as emp from '../assets/emp.js'
import qs from 'qs'
import { ElMessage,ElMessageBox } from 'element-plus'

//页面打开时查询所有员工
onMounted(()=>{
    query()
})



//查询条件
const searchForm=reactive({
    name : '',
    salary : '',
    pageNo : 1,
    pageSize : 2
})

//分页数据
// const pageModel = reactive({
//   "total": 2,
//   "tableData": [
//     {
//       "id": 1,
//       "name": "abc",
//       "salary": 9999,
//       "sex": "1",
//       "edu": "1",
//       "hobbies": [
//         "1",
//         "3"
//       ],
//       "description": "abcd",
//       "hireDate": "2025-10-27",
//       "status": "1"
//     },
//     {
//       "id": 2,
//       "name": "aaa",
//       "salary": 6666,
//       "sex": "0",
//       "edu": "3",
//       "hobbies": [
//         "1",
//         "2",
//         "3"
//       ],
//       "description": "aaaa",
//       "hireDate": "2025-10-28",
//       "status": "0"
//     }
//   ]
// })


const pageModel = reactive({
  "total": 0,
  "tableData": []
})

//分页改变pageSize
const handleSizeChange = (pageSize) => {
    console.log('handleSizeChange')
    searchForm.pageSize=pageSize
    searchForm.pageNo=1
    query()
}
//分页改变pageNo
const handleCurrentChange = (pageNo) => {
    console.log('handleCurrentChange')
    searchForm.pageNo=pageNo
    query()
}

//表格性别格式化
function sexFormatter(row,column,cellValue){
    const sexMap={
        '1' : '男',
        '0' : '女'
    }
    return sexMap[cellValue] || ''
}

//表格日期格式化
function dateFormatter(row,column,cellValue){
    if(cellValue){
        let arr=cellValue.split('-');
        return arr[0]+'年'+arr[1]+'月'+arr[2]+'日'
    }
}

//表格状态标签类型
function getStatusTagType(status){
    const statusMap={
        '1' : 'success',
        '0' : 'danger'
    }
    return statusMap[status] || 'info'
}

//新增模态框，默认不显示
const dialogAddFormVisible = ref(false)

//员工表单数据
const empForm=reactive({
    id : '',
    name : '',
    salary : '',
    sex : '',
    edu : '',
    hobbies : [],
    description : '',
    hireDate : ''
})

//学历
const options=reactive([
    {
        value : '1',
        label : '本科'
    },
        {
        value : '2',
        label : '硕士'
    },
        {
        value : '3',
        label : '博士'
    }
])

//爱好全选
const checkAll = ref(false)
const isIndeterminate = ref(false)
const handleCheckAllChange = (val) => {
    empForm.hobbies = val ? ['1','2','3'] : []
    isIndeterminate.value = false
}

//兴趣爱好全选复选框状态
const handleCheckedHobbiesChange = (value) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === hobbies.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < hobbies.length
}


//爱好
const hobbies = reactive([
    {
        value : '1',
        label : '吃'
    },
        {
        value : '2',
        label : '玩'
    },
        {
        value : '3',
        label : '睡'
    },
])


//清除数据
function clear(){
    console.log('clear')
    dialogAddFormVisible.value=false
    dialogEditFormVisible.value=false
    isIndeterminate.value=false
    checkAll.value=false
    Object.assign(empForm,{
        id : '',
        name : '',
        salary : '',
        sex : '',
        edu : '',
        hobbies : [],
        description : '',
        hireDate : ''
    })

}

//添加操作
function add(){
    console.log('add')
    emp.add(qs.stringify(empForm))
        .then(res=>{
            ElMessage({
                type: 'success',
                message: '添加成功',
                duration: 500
            })
            clear()
            query()
        })
}

//条件查询
function find(){
    console.log('find')
    searchForm.pageNo=1
    query()
}



//条件查询功能
function query(){
    emp.find(searchForm)
        .then(res=>{
            pageModel.total=res.data.total
            pageModel.tableData=res.data.emps
        })
}

//修改状态
function modifyStatus(status){
    console.log('modifyStatus')

    if(!currentRow.value){
        ElMessage({
            message: '请选中一行',
            type: 'warning',
        })
        return;
    }
    emp.modifyStatus(currentRow.value.id,status)
        .then(res=>{
            currentRow.value.status=status
            ElMessage({
                message: '恭喜你，修改成功',
                type: 'success',
                duration: 500
            })
        })
}

//选中行
const currentRow=ref()
const  handlerCurrentRowChange = (emp) => {
  currentRow.value = emp
}

//删除
function remove(row){
    console.log('remove')
    ElMessageBox.confirm(
        '此操作将永久删除该用户，是否继续？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
        )
        .then(() => {
            emp.remove(row.id)
                .then(res=>{
                    query()
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                        duration: 500
                    })
                })
            
            })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
                duration: 500
            })
        })
}

//修改模态框，默认不显示
const dialogEditFormVisible=ref(false)


//打开修改模态框
function showModify(row){
    console.log('showModify')
    
    if(!row.hobbies){
        row.hobbies=[]
    }

    Object.assign(empForm,row)

    handleCheckedHobbiesChange(row.hobbies)

    dialogEditFormVisible.value=true
}

//修改
function modify(){
    console.log('modify')
    emp.modify(qs.stringify(empForm))
        .then(res=>{
            clear()
            query()
            ElMessage({
                message: '恭喜你，修改成功',
                type: 'success',
                duration: 500
            })
        })
}



</script>